package net.mfjassociates.financial;

import java.io.CharArrayReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.stream.XMLStreamException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.xml.sax.InputSource;

public class TestNet {
	private static final String RBC_URL = "https://www1.royalbank.com/cgi-bin/rbaccess/rbunxcgi%3FF6=1%26F7=IB%26F21=IB%26F22=IB%26REQUEST=ClientSignin%26LANGUAGE=ENGLISH";

	public static void main(String[] args) throws XPathExpressionException, XMLStreamException, IOException {
		URL url=null;
		if (args.length==0) {
			url = new URL(RBC_URL);
		} else {
			url = new URL(args[0]);
		}
		System.out.println(retrieveToken());
	}
	static String retrieveToken() throws IOException, XPathExpressionException {

		String response = "";
		URL url=new URL(RBC_URL);
		String html=retrieve(url);
        if ( html != null ) {

        	XPath xpath = XPathFactory.newInstance().newXPath();
            String expression = "/input[@name='SST']/@value";
            InputSource is = new InputSource();
        	
            Pattern p = Pattern.compile("<input[^>]*");
            Matcher m = p.matcher(html);
            while(m.find()) {
            	String input=html.substring(m.start(), m.end()+1);
            	CharArrayReader characterStream = new CharArrayReader(input.toCharArray());
                is.setCharacterStream(characterStream);
                Node node = (Node) xpath.evaluate(expression, is,  XPathConstants.NODE);
                if (node!=null) {
                    response=node.getNodeValue();
/*    				System.out.println(html.substring(m.start(), m.end()+1));
    				System.out.println(response);
*/    				break;
                }
			}
        }
        return response;
	}
	static String retrieve(URL url) throws IOException {
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        String MIMEtype  = null;
        String charset   = null;
        Object content   = null;
        String html		 = null;
        // Set up a request.
        conn.setConnectTimeout( 10000 );    // 10 sec
        conn.setReadTimeout( 10000 );       // 10 sec
        conn.setInstanceFollowRedirects( true );
        conn.setRequestProperty( "User-agent", "spider" );
 
        // Send the request.
        conn.connect( );
        
        // Get the response.
        final int length  = conn.getContentLength( );
        final String type = conn.getContentType( );
        if ( type != null ) {
            final String[] parts = type.split( ";" );
            MIMEtype = parts[0].trim( );
            for ( int i = 1; i < parts.length && charset == null; i++ ) {
                final String t  = parts[i].trim( );
                final int index = t.toLowerCase( ).indexOf( "charset=" );
                if ( index != -1 )
                    charset = t.substring( index+8 );
            }
        }
 
        // Get the content.
        final java.io.InputStream stream = conn.getErrorStream( );
        if ( stream != null )
            content = readStream( length, stream, charset );
        else if ( (content = conn.getContent( )) != null &&
            content instanceof java.io.InputStream )
            content = readStream( length, (java.io.InputStream)content, charset );
        if (content instanceof String) return (String) content;
		return null;
	}
    /** Read stream bytes and transcode. 
     * @param charset TODO*/
    static Object readStream( int length, java.io.InputStream stream, String charset )
        throws java.io.IOException {
        final int buflen = Math.max( 500000, Math.max( length, stream.available() ) );
        byte[] buf   = new byte[buflen];;
        byte[] bytes = null;
 
        for ( int nRead = stream.read(buf); nRead != -1; nRead = stream.read(buf) ) {
            if ( bytes == null ) {
                bytes = buf;
                buf   = new byte[buflen];
                continue;
            }
            final byte[] newBytes = new byte[ bytes.length + nRead ];
            System.arraycopy( bytes, 0, newBytes, 0, bytes.length );
            System.arraycopy( buf, 0, newBytes, bytes.length, nRead );
            bytes = newBytes;
        }
 
        if ( charset == null )
            return bytes;
        try {
            return new String( bytes, charset );
        }
        catch ( java.io.UnsupportedEncodingException e ) { }
        return bytes;
    }
}
